import editForm from "../form.vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { h, onMounted, reactive, ref } from "vue";
import { handleTree } from "@/utils/tree";
import { isAllEmpty, deviceDetection, cloneDeep } from "@pureadmin/utils";
import { addDialog } from "@/components/ReDialog";
import { message } from "@/utils/message";
import type { FormItemProps } from "./type";
import {
  menusAdd,
  menusDelete,
  menusGetAllList,
  menusUpdate
} from "@/api/menu";

export default function useColumns() {
  // 表单配置
  const formRef = ref();
  const form = reactive({
    title: ""
  });

  // 加载状态
  const loading = ref(true);
  const dataList = ref([]);
  const getMenuType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "菜单" : "primary";
      case 1:
        return text ? "iframe" : "warning";
      case 2:
        return text ? "外链" : "danger";
      case 3:
        return text ? "按钮" : "info";
    }
  };

  // 表格列配置
  const columns: TableColumnList = [
    {
      label: "菜单名称",
      prop: "title",
      align: "left",
      cellRenderer: ({ row }) => (
        <>
          <span class="inline-block mr-1">
            {h(useRenderIcon(row.icon), {
              style: { paddingTop: "1px" }
            })}
          </span>
          <span>{row.title}</span>
        </>
      )
    },
    {
      label: "菜单类型",
      prop: "menuType",
      width: 100,
      // 单元格处理 tsx
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={getMenuType(row.menuType)}
          effect="plain"
        >
          {getMenuType(row.menuType, true)}
        </el-tag>
      )
    },
    {
      label: "路由路径",
      prop: "path"
    },
    {
      label: "组件路径",
      prop: "component"
    },
    {
      label: "权限标识",
      prop: "auths"
    },
    {
      label: "排序",
      prop: "rank",
      width: 100
    },
    {
      label: "隐藏",
      prop: "showLink",
      width: 100,
      formatter: ({ showLink }) => (showLink ? "否" : "是")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  // 搜索
  const onSearch = async () => {
    loading.value = true;
    let { data }: any = await menusGetAllList();
    if (!isAllEmpty(form.title)) {
      // 前端搜索菜单名称
      data = data.filter(item => item.title.includes(form.title));
    }
    dataList.value = handleTree(data); // 处理成树结构
    setTimeout(() => {
      loading.value = false;
    }, 500);
  };

  // 新增修改
  const openDialog = (title = "新增", row?: FormItemProps) => {
    addDialog({
      title: `${title}菜单`,
      props: {
        formInline: {
          id: row?.id ?? "",
          menuType: row?.menuType ?? 0,
          higherMenuOptions: formatHigherMenuOptions(cloneDeep(dataList.value)),
          parentId: row?.parentId ?? "0",
          title: row?.title ?? "",
          name: row?.name ?? "",
          path: row?.path ?? "",
          component: row?.component ?? "",
          rank: row?.rank ?? 99,
          redirect: row?.redirect ?? "",
          icon: row?.icon ?? "",
          extraIcon: row?.extraIcon ?? "",
          enterTransition: row?.enterTransition ?? "",
          leaveTransition: row?.leaveTransition ?? "",
          activePath: row?.activePath ?? "",
          auths: row?.auths ?? "",
          frameSrc: row?.frameSrc ?? "",
          frameLoading: row?.frameLoading ?? true,
          keepAlive: row?.keepAlive ?? false,
          hiddenTag: row?.hiddenTag ?? false,
          fixedTag: row?.fixedTag ?? false,
          showLink: row?.showLink ?? true,
          showParent: row?.showParent ?? false
        }
      },
      width: "45%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了菜单名称为${curData.title}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              menusAdd(curData).then(res => {
                if (res.success) {
                  chores();
                }
              });
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              menusUpdate(curData).then(res => {
                if (res.success) {
                  chores();
                }
              });
            }
          }
        });
      }
    });
  };

  // 删除
  const handleDelete = async row => {
    await menusDelete({ id: row.id }).then(res => {
      if (res.success) {
        message("删除成功", {
          type: "success"
        });
        onSearch(); // 刷新表格数据
      }
    });
  };

  // 重置表单
  const resetForm = formEl => {
    formEl.resetFields();
  };

  function formatHigherMenuOptions(treeList) {
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].title = treeList[i].title;
      formatHigherMenuOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  }

  onMounted(() => {
    onSearch();
  });

  // 这里可以写一些逻辑
  return {
    form,
    loading,
    dataList,
    columns,
    onSearch,
    openDialog,
    handleDelete,
    resetForm
  };
}
